package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Operator;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.OperatorMapper;
import cn.wolfcode.crm.service.IOperatorService;
import cn.wolfcode.crm.util.PageResult;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OperatorServiceImpl implements IOperatorService {
    @Autowired
    private OperatorMapper operatorMapper;


    public void save(Operator operator) {
        String password = new Md5Hash(operator.getPassword(), operator.getUsername()).toString();

        operator.setPassword(password);

        try {
            operatorMapper.insert(operator);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void update(Operator operator) {
        operatorMapper.updateByPrimaryKey(operator);
    }

    public void delete(Long id) {
        operatorMapper.deleteByPrimaryKey(id);
    }

    public Operator get(Long id) {

        return operatorMapper.selectByPrimaryKey(id);
    }

    public PageResult list() {
        List<Operator> rows = operatorMapper.selectAll();
        System.out.println(rows.toString());

        return new PageResult(rows.size(), rows);
    }

    @Override
    public List<Operator> listAll() {
        return operatorMapper.selectAll();
    }

    public void insertOperatorRole(Operator operator) {
        Long operatorId = operator.getId();

        if(operator!=null){
            List<Role> roles = operator.getRoles();
            for (Role role : roles) {
                Long roleId = role.getId();
                operatorMapper.insertOperatorRole(operatorId,roleId);
            }
        }
    }

    public void updateOperatorRole(Operator operator) {
        Long operatorId = operator.getId();
        operatorMapper.deleteOperatorRole(operator.getId());
        if(operator!=null){
            List<Role> roles = operator.getRoles();
            for (Role role : roles) {
                Long roleId = role.getId();
                operatorMapper.insertOperatorRole(operatorId,roleId);
            }
        }
    }

    public void deleteOperatorRole(Long id) {
        operatorMapper.deleteOperatorRole(id);
    }


}
